<template>
	<div class="system-add-menu-container">
		<el-dialog :title="props.type === 0 ? '新增菜单' : '编辑菜单'" :model-value="props.modelValue" width="769px" :before-close="handleClose">
			<el-form :model="ruleForm" ref="ruleFormRef" :rules="rules" size="default" label-width="80px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="上级菜单">
							<el-cascader
								:options="menuData"
								:props="{ checkStrictly: true, value: 'id', label: 'title' }"
								placeholder="请选择上级菜单"
								clearable
								class="w100"
								v-model="ruleForm.menuSuperior"
							>
								<template #default="{ node, data }">
									<span>{{ data.meta.title }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="菜单类型">
							<el-radio-group v-model="ruleForm.menuType">
								<el-radio :label="0">菜单</el-radio>
								<el-radio :label="1">按钮</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item :label="ruleForm.menuType === 0 ? '菜单名称' : '按钮名称'" prop="title">
							<el-input v-model="ruleForm.title" placeholder="请输入名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<template v-if="ruleForm.menuType === 0">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="路由名称" prop="name">
								<el-input v-model="ruleForm.name" placeholder="请输入路由名称" clearable>
									<template #append>
										<el-tooltip placement="bottom">
											<el-button>?</el-button>
											<template #content>
												路由中的name值:<br />
												需和引入组件的name对应<br />
												否则会导致缓存组件失败</template
											>
										</el-tooltip>
									</template>
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="路由路径" prop="path">
								<el-input v-model="ruleForm.path" placeholder="请输入路由路径" clearable>
									<template #append>
										<el-tooltip placement="bottom">
											<el-button>?</el-button>
											<template #content>
												路由中的path值:<br />
												有children时, path字段是基于上一级继续拼接<br />
												如下所示：<br />
												一级:/system<br />
												二级:/system/menu<br />
											</template>
										</el-tooltip>
									</template>
								</el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="组件路径" prop="component">
								<el-input v-model="ruleForm.component" placeholder="请输入组件路径" clearable :disabled="ruleForm.isLinkRadio">
									<template #append>
										<el-tooltip placement="bottom">
											<el-button>?</el-button>
											<template #content
												>路由中的组件引入路径:<br />
												1、layout:以 layout 开头的话，去掉了 @/ 及 .vue 后缀<br />
												2、views:以 views 开头的话，去掉了 @/views/ 及 .vue 后缀<br />
												3、只要当前级下有子级children,那么当前级为layout/routerView/parent写死路径<br />
												4、外链:外链组件地址为:layout/routerView/link,链接地址必填<br />
												5、内嵌:内嵌组件地址为:layout/routerView/iframes,链接地址必填<br />
											</template>
										</el-tooltip>
									</template>
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜单图标">
								<IconSelector placeholder="请输入菜单图标" v-model="ruleForm.icon" type="all" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="重定向">
								<el-input v-model="ruleForm.redirect" placeholder="请输入路由重定向" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="链接地址">
								<el-input v-model="ruleForm.isLink" placeholder="外链/内嵌时链接地址（http:xxx.com）" clearable :disabled="!ruleForm.isLinkRadio">
								</el-input>
							</el-form-item>
						</el-col>
						<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="权限标识">
								<el-select v-model="ruleForm.roles" multiple placeholder="取角色管理" clearable class="w100">
									<el-option label="admin" value="admin"></el-option>
									<el-option label="common" value="common"></el-option>
								</el-select>
							</el-form-item>
						</el-col> -->
					</template>
					<template v-if="ruleForm.menuType === 1">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="权限标识" prop="btnPower">
								<el-input v-model="ruleForm.btnPower" placeholder="请输入权限标识" clearable>
									<template #append>
										<el-tooltip placement="bottom">
											<el-button>?</el-button>
											<template #content
												>按钮权限标识:<br />
												用于前端指令检查<br />
												格式例如:system.menu.add<br />
											</template>
										</el-tooltip>
									</template>
								</el-input>
							</el-form-item>
						</el-col>
					</template>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="排序">
							<el-input-number v-model="ruleForm.menuSort" controls-position="right" placeholder="请输入排序" class="w100" />
						</el-form-item>
					</el-col>
					<template v-if="ruleForm.menuType === 0">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="是否隐藏">
								<el-radio-group v-model="ruleForm.isHide">
									<el-radio :label="true">隐藏</el-radio>
									<el-radio :label="false">不隐藏</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="页面缓存">
								<el-radio-group v-model="ruleForm.isKeepAlive">
									<el-radio :label="true">缓存</el-radio>
									<el-radio :label="false">不缓存</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="是否固定">
								<el-radio-group v-model="ruleForm.isAffix">
									<el-radio :label="true">固定</el-radio>
									<el-radio :label="false">不固定</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="是否外链">
								<el-radio-group v-model="ruleForm.isLinkRadio" @change="onSelectIsLinkChange" :disabled="ruleForm.isIframe">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="是否内嵌">
								<el-radio-group v-model="ruleForm.isIframe" @change="onSelectIframeChange">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(ruleFormRef)" size="default">{{ props.type === 0 ? '新 增' : '确 定' }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="systemAddMenu">
import { storeToRefs } from 'pinia';
import { useRoutesList } from '@/stores/routesList';
import IconSelector from '@/components/iconSelector/index.vue';
import { addMenu, editMenu } from '@/api/system/menu';
import { ElMessage } from 'element-plus';
import { initBackEndControlRoutes } from '@/router/backEnd';
const emits = defineEmits(['update:modelValue', 'refresh']);
const props = defineProps({
	modelValue: {
		type: Boolean,
	},
	menuDataList: {
		type: Array,
		default: () => [],
	},
	editData: {
		type: Object,
		default: () => {},
	},
	type: {
		type: Number,
		default: 0,
	},
});

// console.log(props.editData);
// console.log(props.type);

// 知道子id获取全部父级id
const getTreeIds = (tree, nodeId, config) => {
	const { children = 'children', id = 'id' } = config || {};
	const toFlatArray = (tree, parentId) => {
		return tree.reduce((t, _) => {
			const child = _[children];
			return [...t, parentId ? { ..._, parentId } : _, ...(child && child.length ? toFlatArray(child, _[id]) : [])];
		}, []);
	};
	const getIds = (flatArray) => {
		let ids = [nodeId];
		let child = flatArray.find((_) => _[id] === nodeId);
		while (child && child.parentId) {
			ids = [child.parentId, ...ids];
			child = flatArray.find((_) => _[id] === child.parentId);
		}
		return ids;
	};
	return getIds(toFlatArray(tree));
};

onMounted(() => {
	if (props.type === 0 && props.editData) {
		ruleForm.menuSuperior = getTreeIds(props.menuDataList, props.editData.id); // 上级菜单
	} else if (props.type === 1 && props.editData) {
		let a = getTreeIds(props.menuDataList, props.editData.id);
		a.pop();
		ruleForm.title = props.editData.meta.title; // 菜单名称
		ruleForm.name = props.editData.name; // 路由名称
		ruleForm.menuSuperior = a; // 上级菜单
		ruleForm.menuSort = props.editData.sort; // 菜单排序
		ruleForm.icon = props.editData.meta.icon; // 菜单图标
		ruleForm.path = props.editData.path; // 路由路径
		ruleForm.component = props.editData.component; // 组件路径
		ruleForm.isIframe = !!props.editData.meta.isIframe; // 是否内嵌，开启条件，`1、isIframe=true 2、isLink：链接地址不为空`
		ruleForm.isLink = props.editData.meta.isLink; // 外链地址/内嵌时链接地址（http=xxx.com），开启条件，`1、isLink= 链接地址不为空`
		ruleForm.isLinkRadio = !!props.editData.meta.isLink; // 是否开启外链/内嵌?，开启外链条件，`1、isLink= 链接地址不为空`
		ruleForm.menuType = props.editData.type; // 菜单类型/0菜单1按钮
		ruleForm.isHide = !!props.editData.meta.isHide; // 是否隐藏
		ruleForm.isKeepAlive = !!props.editData.meta.isKeepAlive; // 是否缓存
		ruleForm.isAffix = !!props.editData.meta.isAffix; // 是否固定
		ruleForm.btnPower = props.editData.type === 1 ? props.editData.permission : ''; // 菜单类型为按钮时，权限标识
		ruleForm.status = 0; //状态：0-正常，1-禁用
		ruleForm.remark = ''; //备注
		ruleForm.redirect = props.editData.redirect; // 路由重定向，有子集 children 时
	}
	console.log(ruleForm.menuSuperior);
});

const ruleFormRef = ref(null);
const ruleForm = reactive({
	// 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由菜单格式
	title: '', // 菜单名称
	name: '', // 路由名称
	menuSuperior: [], // 上级菜单
	menuSort: 0, // 菜单排序
	icon: '', // 菜单图标
	path: '', // 路由路径
	component: '', // 组件路径
	isIframe: false, // 是否内嵌，开启条件，`1、isIframe:true 2、isLink：链接地址不为空`
	isLink: '', // 外链地址/内嵌时链接地址（http:xxx.com），开启外链条件，`1、isLink: 链接地址不为空`
	isLinkRadio: false, // 是否开启外链/内嵌?，开启外链条件，`1、isLink: 链接地址不为空`
	menuType: 0, // 菜单类型/0菜单,1按钮
	isHide: false, // 是否隐藏
	isKeepAlive: true, // 是否缓存
	isAffix: false, // 是否固定
	btnPower: '', // 菜单类型为按钮时，权限标识
	status: 0, //状态：0-正常，1-禁用
	remark: '', //备注
	redirect: '', // 路由重定向，有子集 children 时
});

const rules = reactive({
	title: [
		{ required: true, message: '此项必填', trigger: 'blur' },
		{ min: 1, max: 8, message: '长度不能超过20个字符', trigger: 'blur' },
	],
	name: [{ required: true, message: '此项必填', trigger: 'blur' }],
	path: [{ required: true, message: '此项必填', trigger: 'blur' }],
	component: [{ required: true, message: '此项必填', trigger: 'blur' }],
	btnPower: [{ required: true, message: '此项必填', trigger: 'blur' }],
});

// 获取路由
const menuData = ref(JSON.parse(JSON.stringify(props.menuDataList)));
const getMenuData = (routes) => {
	const arr = [];
	routes.map((val) => {
		val['title'] = val.meta.title;
		arr.push({ ...val });
		if (val.children.length) getMenuData(val.children);
	});
	return arr;
};
menuData.value = getMenuData(menuData.value);

// 是否内嵌下拉改变
const onSelectIframeChange = () => {
	if (ruleForm.isIframe) {
		ruleForm.isLinkRadio = true;
		ruleForm.isLink = props.editData ? props.editData.meta.isLink : '';
		ruleForm.component = 'layout/routerView/iframes';
	} else {
		ruleForm.isLinkRadio = false;
		ruleForm.isLink = '';
		ruleForm.component = props.editData ? props.editData.component : '';
	}
};
// 是否外链下拉改变
const onSelectIsLinkChange = () => {
	if (ruleForm.isLinkRadio) {
		ruleForm.component = 'layout/routerView/link';
		ruleForm.isLink = props.editData ? props.editData.meta.isLink : '';
	} else {
		ruleForm.isLink = '';
		ruleForm.component = props.editData ? props.editData.component : '';
	}
};
// 取消
const onCancel = () => {
	handleClose();
};
// 新增/编辑
const onSubmit = (formEl) => {
	if (!formEl) return;
	formEl.validate(async (valid) => {
		if (valid) {
			let params = {
				title: ruleForm.title,
				name: ruleForm.name,
				parent_id: ruleForm.menuSuperior.length ? ruleForm.menuSuperior[ruleForm.menuSuperior.length - 1] : '',
				sort: ruleForm.menuSort,
				icon: ruleForm.icon,
				path: ruleForm.path,
				component: ruleForm.component,
				is_iframe: ruleForm.isIframe,
				is_link: ruleForm.isLink,
				type: ruleForm.menuType,
				is_hide: ruleForm.isHide,
				is_keep_alive: ruleForm.isKeepAlive,
				is_affix: ruleForm.isAffix,
				permission: ruleForm.btnPower,
				status: ruleForm.status,
				remark: ruleForm.remark,
				redirect: ruleForm.redirect,
			};
			let res;
			if (props.type === 0) {
				res = await addMenu(params);
			} else {
				params.id = props.editData.id;
				res = await editMenu(params);
			}
			console.log(res);
			if (res.code === 0) {
				ElMessage.success(res.message);
				handleClose(); // 关闭弹窗
				initBackEndControlRoutes(); // 刷新菜单，未进行后端接口测试
				emits('refresh');
			} else {
				ElMessage.error(res.message);
			}
		}
	});
};

// 关闭弹窗
const handleClose = () => {
	emits('update:modelValue', false);
};
</script>
